import Koa from 'koa';
import config from './config/index.js';
import bodyParser from 'koa-bodyparser';
import errorHandler from './middlewares/errorHandler.js';
import connectDB from './config/db.js';
import router from './routes/api.js';
import { koaSwagger } from 'koa2-swagger-ui';
console.log("🚀 ~ koaSwagger:", koaSwagger);

const app = new Koa();

// 初始化数据库
connectDB();

const startServer = (port = 3000) => {
  app.listen(port, () => {
    console.log(`Listening on port ${port}`);
  }).on('error', (err) => {
    if (err.code === 'EADDRINUSE') {
      console.log(`Port ${port} is in use, trying ${port + 1}`);
      startServer(port + 1);
    }
  });
};
startServer(config.app.port);
app.use(bodyParser());

app.use(
  koaSwagger({
    routePrefix: "/swagger",
    swaggerOptions: {
      url: "/api/swagger.json",
    },
  })
);

// 中间件
app.use(errorHandler());

// 路由
app.use(router.routes()).use(router.allowedMethods());